
<template>
    <base-breadcrumb>
        <a-spin :spinning="tableLoading">
            <a-card>
                <titleName title="基本信息"></titleName>
                <a-form-model ref="ruleForm" :model="form" :rules="rules" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                    :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }">
                    <a-row :gutter="24">
                        <a-col span="16">
                            <a-form-model-item label="所属单位" prop="projectId">
                                <org-tree-select v-model="form.projectId"  checkStrictly disabled
                                  ></org-tree-select>
                                <!-- :disabled="pageType == 'looks'" -->
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="名称" prop="name">
                                <a-input v-model="form.name" disabled />
                            </a-form-model-item>
                        </a-col>
                        <div  v-show="isNewProject">
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="净现金流（元）：" prop="netCashFlow">
                                <a-input-number :precision="2" v-model="form.netCashFlow" :disabled="pageType == 'looks' || isNewProject" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="填报人" prop="informant">
                                <a-input v-model="form.informant" disabled />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item  label="填报时间：" prop="informantDate">
                                <a-date-picker v-model="form.informantDate" disabled
                                    @change="(date, dateString) => getTime(date, dateString, 'form', 'informantDate')" />
                                <!-- <a-input  v-model="form.informantTime" :disabled="pageType == 'looks'" /> -->
                            </a-form-model-item>
                        </a-col>
                        <!-- 表格填写内容 -->
                        <a-col :md="24" :sm="24">
                            <a-table :columns="columns" :data-source="dataSource" bordered :pagination='isshow'>
                                <span slot="age" slot-scope="text, record, index" class="requiredFormItem">
                                    <a-input-number v-model="record.a" style="width: 95%;" :disabled="record.disabled || pageType == 'looks'"
                                        @change="handleSum($event, record)" />
                                </span>
                                <span slot="address" slot-scope="text, record, index" class="requiredFormItem">
                                    <a-input-number v-model="record.b" style="width: 95%;" :disabled="record.disabled || pageType == 'looks'"
                                        @change="handleSum($event, record)" />
                                </span>
                                <span slot="tags" slot-scope="text, record, index" class="requiredFormItem">
                                    <a-input-number v-model="record.c" style="width: 95%;" :disabled="record.disabled || pageType == 'looks'"
                                        @change="handleSum($event, record)" />
                                </span>

                                <span slot="action" slot-scope="text, record, index">
                                    <a-input-number v-model="record.d" disabled style="width: 95%;" />
                                </span>

                            </a-table>
                        </a-col>
                        <a-col :md="8" :sm="8" style="margin-top: 20px;">
                            <a-form-model-item label="工程计量确认率（%）：" prop="projectMeasureConfirmRate">
                                <a-input-number :precision="2" v-model="form.projectMeasureConfirmRate" disabled />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="24" :sm="24">
                            <a-form-model-item label="备注" prop="remark" :labelCol="{ lg: { span: 5 }, sm: { span: 5 } }"
                                :wrapperCol="{ lg: { span: 18 }, sm: { span: 17 } }">
                                <!-- <BaseTextarea :auto-size="{ minRows: 3, maxRows: 5 }" v-model="form.participants" /> -->
                                <a-input v-model="form.remark" type="textarea" :disabled="pageType == 'looks'" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="24" :sm="24">
                            <a-form-model-item label="附件上传">
                                <upload-list :businessCode="'BM19'" :disabled="pageType == 'looks'"
                                    :uploadArrys.sync="form.files" @fileArrysData="handleFileUploaded"
                                    multiple></upload-list>
                            </a-form-model-item>
                        </a-col>
                    </div>
                    </a-row>
                </a-form-model>
            </a-card>
            <div class="tool-btns page-btn-right-top" v-if="!isAudit && !isConsultation">

            <!-- <a-button v-if="pageType !== 'looks'" type="primary"  :loading="loading.SUBMITTED" @click="handleSave('DRAFT')"
          >保存草稿</a-button
                > -->
                <a-button type="primary" v-if="pageType !== 'looks'" :loading="loading.SUBMITTED"
                    @click="handleSave('SUBMITTED')">提交</a-button>
                <a-button @click="handleClose">关闭</a-button>
            </div>
        </a-spin>
        <selectApprover :businessId="businessId" :processConfig="setProcessConfig"></selectApprover>
    </base-breadcrumb>
</template>
<script>

import { STable } from '@/components'
import UploadList from '@/components/UploadList'
// import { LookCostPlanning, saveCostPlanning } from '@/api/businessAffairs/designPlanning'
import { lookList, saveList,checkBudgetAnalysis} from '@/api/businessAffairs/szAnalysis'
import moment from 'moment'
const columns = [
    {
        title: '项目/金额',
        dataIndex: 'je',
    },
    {
        title: '当期发生金额（元）',
        dataIndex: 'age',
        scopedSlots: { customRender: 'age' },
    },
    {
        title: '累计发生金额（元）',
        dataIndex: 'address',
        scopedSlots: { customRender: 'address' },
    },
    {
        title: '后期发生金额（元）',
        dataIndex: 'tags',
        scopedSlots: { customRender: 'tags' },
    },
    {
        title: '合计',
        key: 'action',
        scopedSlots: { customRender: 'action' },
    },
];
export default {
    name: 'a' + Date.now(),
    components: {
        STable,
        UploadList,
    },
    data() {
        this.columns = columns
        return {
            isshow: false,
            dataSource: [{
                je: '预计总收入（不含税）',
                a: 0,
                b: 0,
                c: 0,
                d: 0,
                index: 0
            }, {
                je: '预计总成本（不含税）',
                a: 0,
                b: 0,
                c: 0,
                d: 0,
                index: 1
            }, {
                je: '销项税',
                a: 0,
                b: 0,
                c: 0,
                d: 0,
                index: 2
            }, {
                je: '进项税',
                a: 0,
                b: 0,
                c: 0,
                d: 0,
                index: 3
            }, {
                je: '附加税',
                a: 0,
                b: 0,
                c: 0,
                d: 0,
                index: 4
            }, {
                je: '应交税金',
                disabled: true,
                a: 0,
                b: 0,
                c: 0,
                d: 0,
                index: 5
            }, {
                je: '利润额（含税）',
                disabled: true,
                a: 0,
                b: 0,
                c: 0,
                d: 0,
                index: 6
            },
            {
                je: '利润率（含税）（%）',
                disabled: true,
                a: 0,
                b: 0,
                c: 0,
                d: 0,
                index: 7
            }
            ],
            tableLoading: false,
            loading: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                REJECTED: false
            },
            form: {
                projectId: '',
                name: '',
                netCashFlow: '',
                projectMeasureConfirmRate: '',
                informant: '',
                informantDate: '',
                remark: '',

            },
            rules: {
                netCashFlow: [{ required: true, message: '请输入' }],
                // purchasedBenefitRate: [{ required: true, message: '请输入' }],
                // targetBenefit: [{ required: true, message: '请输入' }],
                // targetBenefitRate: [{ required: true, message: '请输入' }],
                // finishedDate: [{ required: true, message: '请选择', change: true }]
            },
            id: '',
            pageType: '',

            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null,
            yearMonth:null,
            isNewProject:false, //是否新开项目
            isMonthlySubmit:false,//商务成本信息填写（月度）是否提交
        }
    },

    props: {
        // 是否作为审批详情
        isAudit: {
            type: Boolean,
            default: false
        },
        // 是否作为意见征询
        isConsultation: {
            type: Boolean,
            default: false
        },
    },
    async created() {
        this.pageType = this.$route.query.pageType
        if (this.$route.query.businessId) {
            this.pageType = 'looks'
        }
        this.getLists()
    },
    methods: {
        handleSum(val, row) {
            row.d = Number(row.b) + Number(row.c)
            // 行的数据
            const row0 = this.dataSource[0]
            const row1 = this.dataSource[1]
            const row2 = this.dataSource[2]
            const row3 = this.dataSource[3]
            const row4 = this.dataSource[4]
            const row5 = this.dataSource[5]
            const row6 = this.dataSource[6]
            const row7 = this.dataSource[7]
            //应缴税金
            row5.a = Number(row2.a) - Number(row3.a) + Number(row4.a)
            row5.b = Number(row2.b) - Number(row3.b) + Number(row4.b)
            row5.c = Number(row2.c) - Number(row3.c) + Number(row4.c)
            row5.d = Number(row2.d) - Number(row3.d) + Number(row4.d)
            //利润额（含税
            row6.a = Number(row0.a) - Number(row1.a) - Number(row5.a)
            row6.b = Number(row0.b) - Number(row1.b) - Number(row5.b)
            row6.c = Number(row0.c) - Number(row1.c) - Number(row5.c)
            row6.d = Number(row0.d) - Number(row1.d) - Number(row5.d)

            //利润率（含税）（%
            if ((Number(row0.a) + Number(row2.a)) > 0) {
                row7.a = ((Number(row6.a) / (Number(row0.a) + Number(row2.a))) * 100).toFixed(2)
            } else {
                row7.a = ""
            }

            // 利润率2
            if ((Number(row0.b) + Number(row2.b)) > 0) {
                row7.b = ((Number(row6.b) / (Number(row0.b) + Number(row2.b))) * 100).toFixed(2)
            } else {
                row7.b = ""
            }
            // 利润3
            if ((Number(row0.c) + Number(row2.c)) > 0) {
                row7.c = ((Number(row6.c) / (Number(row0.c) + Number(row2.c))) * 100).toFixed(2)
            } else {
                row7.c = ""
            }
            // 利润4
            if ((Number(row0.d) + Number(row2.d)) > 0) {
                row7.d = ((Number(row6.d) / (Number(row0.d) + Number(row2.d))) * 100).toFixed(2)
            } else {
                row7.d = ""
            }
            if (row0.b > 0 && row1.b > 0) {
                this.form.projectMeasureConfirmRate = (row0.b / row1.b).toFixed(2)
            } else {
                this.form.projectMeasureConfirmRate = ""
            }

        },

        getTime(date, dateString, type, name) {
            this[type][name] = dateString
            console.log(this[type][name])
        },
        // 获取详情
        getLists() {
            // console.log('wwwwwwwwwwwwwwwwwwwww')
            this.tableLoading = true;
            lookList({ id: this.$route.query.id }).then((res) => {
                this.tableLoading = false;
                if (res.code == 200) {
                    // console.log(res, 222222222222222)
                    const data = res.data
                    this.form = data
                    let name = '';
                    if(data.name){
                        name = data.name.slice(0,7);
                        if(name){
                            this.yearMonth = name.replace("年","-");
                        }
                    }
                    this.form.projectId = this.$route.query.projectId
                    this.checkBudgetAnalysisFn();
                    this.form.files = res.data.reviewFileInfoVOList
                    if(this.form.amountJson) {
                        this.dataSource = JSON.parse(this.form.amountJson)
                    }
                    if (this.pageType !== 'looks') {
                        this.form.informant = this.$userInfo().name
                        this.form.informantDate = moment().format("YYYY-MM-DD")
                    }
                }
            })
        },
        checkBudgetAnalysisFn(){
            let req = {
                month:this.yearMonth,
                projectId:this.$route.query.projectId
            }
            checkBudgetAnalysis(req).then((res)=>{
                if(res.code == '0'){
                   this.isMonthlySubmit = res.data.isMonthlySubmit
                   this.isNewProject = !res.data.isNewProject
                }
            })
        },

        handleFileUploaded(list) {
            this.form.files = [...list]
        },

        //获取项目id
        selectOrg(val) {
            if (val && val.length) {
                this.form.branchComId = val[val.length - 2].orgId
            }
        },

        handleClose() {
            // this.$router.replace("/businessAffairs/businessOrganization/costPlanning")
            this.$multiTab.close(this.$route.fullpath)
        },
        handleSave(auditStatus) {
            if(!this.isMonthlySubmit){
                this.$message.warning("请先完成本期的商务成本信息填报(月度)的填报");
                return 
            }
            let flag = true
            this.dataSource.forEach((item,index)=>{
                if(index<5) {
                    for(let key in item) {
                    if(item[key] === '' || item[key] === null) {
                        flag = false
                        break
                    }
                }
               
                }
              
            })
            if(!flag) {
                this.$message.warning("数据填写不完整")
                return
            }
            this.form.auditStatus = auditStatus
            this.form.id = this.$route.query.id
            this.form.amountJson = JSON.stringify(this.dataSource)
            const row0 = this.dataSource[0]
            const row1 = this.dataSource[1]
            const row2 = this.dataSource[2]
            const row3 = this.dataSource[3]
            const row4 = this.dataSource[4]
            const row5 = this.dataSource[5]
            const row6 = this.dataSource[6]
            const row7 = this.dataSource[7]
            // 行转列
            const enumArr = [{
                prop: 'a',
                enum: 'CURRENT_AMOUNT'
            }, {
                prop: 'b',
                enum: 'ACCUMULATED_AMOUNT'
            },{
                prop: 'c',
                enum: 'SUBSEQUENT_AMOUNT'
            }]
            let budgetAnalysisOfAmountVOS = []
            enumArr.forEach((item)=>{
                    let obj = {
                    "expectedIncome": row0[item.prop],
                    "expectedCost": row1[item.prop],
                    "outputTax": row2[item.prop],
                    "inputTax": row3[item.prop],
                    "additionalTax": row4[item.prop],
                    "payableTax": row5[item.prop],
                    "profitAmount": row6[item.prop],
                    "profitMargin": row7[item.prop],
                    budgetAmountEnum: item.enum
                    }
                budgetAnalysisOfAmountVOS.push(obj)
            })
            // console.log(budgetAnalysisOfAmountVOS, 'budgetAnalysisOfAmountVOS')
            let data = {
                ...this.form,
                budgetAnalysisOfAmountDTO: budgetAnalysisOfAmountVOS
            }
            // console.log(data,1111111222222111)
            if (this.form.files <= 0) {
                this.$message.warning("请上传附件")
                return false
            }
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.loading.SUBMITTED = true
                    saveList(data).then(res => {
                        this.loading.SUBMITTED = false
                        if (res.code === 200) {
                            this.$message.success('成功')
                            this.handleClose()
                        } else {
                            this.$message.warning('失败')
                        }
                    })
                } else {
                    this.$message.warning("请填写完所有必填项信息")
                    return false
                }
            })
        }
    }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';

.tool-btns {
    display: flex;
    justify-content: flex-end;

    @{deep} .ant-btn+.ant-btn {
        margin-left: 12px;
    }
}
</style>
  